package com.daniel.juc.add;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/21 09:42
 */
public class BlockingQueueDemo {

	public static void main(String[] args) {
		test04();
	}

	/**
	 * 有返回值，抛出异常
	 */
	public static void test01() {
		// 队列的大小
		ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

		System.out.println(blockingQueue.add("a"));
		System.out.println(blockingQueue.add("b"));
		System.out.println(blockingQueue.add("c"));

		// 检测队首元素
		// System.out.println(blockingQueue.element());

		// IllegalStateException: Queue full 抛出异常
		// System.out.println(blockingQueue.add("d"));

		System.out.println("=======================");

		System.out.println(blockingQueue.remove());
		System.out.println(blockingQueue.remove());
		System.out.println(blockingQueue.remove());
		// NoSuchElementException 抛出异常
		// System.out.println(blockingQueue.remove());
	}

	/**
	 * 有返回值，没有异常
	 */
	public static void test02() {
		// 队列大小
		ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

		System.out.println(blockingQueue.offer("a"));
		System.out.println(blockingQueue.offer("b"));
		System.out.println(blockingQueue.offer("c"));

		// 检测队首元素
		System.out.println(blockingQueue.peek());

		// false 不抛出异常！
		// System.out.println(blockingQueue.offer("d"));

		System.out.println("=======================");

		System.out.println(blockingQueue.poll());
		System.out.println(blockingQueue.poll());
		System.out.println(blockingQueue.poll());

		// null 不抛出异常
		// System.out.println(blockingQueue.poll());
	}

	/**
	 * 等待，阻塞（一直阻塞）
	 */
	public static void test03() {
		// 队列大小
		ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

		try {
			blockingQueue.put("a");
			blockingQueue.put("b");
			blockingQueue.put("c");

			// 队列没有位置，一直阻塞
			// blockingQueue.put("d");

			System.out.println(blockingQueue.take());
			System.out.println(blockingQueue.take());
			System.out.println(blockingQueue.take());
			// 没有这个元素，一直阻塞
			// System.out.println(blockingQueue.take());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 等待，阻塞（等待超时）
	 */
	public static void test04() {
		// 队列大小
		ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

		try {
			System.out.println(blockingQueue.offer("a"));
			System.out.println(blockingQueue.offer("b"));
			System.out.println(blockingQueue.offer("c"));
			// 等待超过2秒就退出
			blockingQueue.offer("d", 2, TimeUnit.SECONDS);

			System.out.println("=======================");

			System.out.println(blockingQueue.poll());
			System.out.println(blockingQueue.poll());
			System.out.println(blockingQueue.poll());
			// 等待超过2秒就退出
			blockingQueue.poll(2, TimeUnit.SECONDS);
			System.out.println("=======================");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


